<?php
namespace App\Services;
use GuzzleHttp\Client;
use App\Models\Kfcorps;
use App\Models\Worklinkenter;
use App\Models\Workkefucursor;
use App\Models\Kflists;
use App\Models\Worklinkwelcome;
use App\Models\Worklinkrecord;
use App\Services\WorkkfService;
use App\Services\WorkService;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cache;
use App\Jobs\Worklinkmsg;
use Log,Exception,Config;

// 处理企业微信客服消息
class WorkkefuService
{
    // 读取最新消息
    public static function syncMsgLists($corp_id,$token)
    {
        // 获取最后一次角标
        $next_cursor = Redis::hget('next_cursor', $corp_id);
        if (empty($next_cursor)) {
            // 获取数据库中最后一次获取的角标,防止卡死
            $lastCursor = Workkefucursor::getKfListsLastCursor($corp_id);
            $next_cursor = isset($lastCursor->cursor) ? $lastCursor->cursor : "";
        }

        $msgs = WorkkfService::kfSyncMsg($corp_id,$next_cursor,$token,100);
        // 马上保存下标,防止并发导致重复获取
        if (isset($msgs->next_cursor)) {
            Redis::hset('next_cursor',$corp_id,$msgs->next_cursor);
        }
        $msgLists = $msgs->msg_list;        
        // 消息过多则交给队列处理
        if (count($msgLists) >= 5) {
            Worklinkmsg::dispatch($msgLists,$corp_id);
        } else {
            self::msgListsHanddle($msgLists,$corp_id);
        }

        // 判断是否有更多数据,但是并发高时无需处理会自动回调
        // if ($msgs["has_more"] > 0) {
        //     self::syncMsgLists($corp_id,$token);
        // }
    }

    // 处理获取到的消息
    public static function msgListsHanddle($msgLists,$corp_id)
    {
        $lasttime = time()-86400;
        foreach ($msgLists as $msgList) {
            if ($lasttime >= $msgList->send_time) {
                continue;
            }
            try {
                // 客户UserID
                $servicer_userid = isset($msgList->servicer_userid) ? $msgList->servicer_userid : "";
                // 接收到文本消息
                if ($msgList->msgtype == "event") {
                    try {
                        // 接收到事件
                        $event_type = $msgList->event->event_type;
                        $open_kfid = $msgList->event->open_kfid;
                        $external_userid = $msgList->event->external_userid;
                        $scene = isset($msgList->event->scene) ? $msgList->event->scene : "";
                        $sceneParams = isset($msgList->event->scene_param) ? json_decode(urldecode($msgList->event->scene_param),true) : ["kfid"=>"","record_id"=>"","back_platfrom"=>""];
                        $back_platfrom = isset($sceneParams["back_platfrom"]) ? $sceneParams["back_platfrom"] : "";
                        // 客户进入客服事件
                        if ($event_type == "enter_session") {
                            // 添加进入记录
                            Worklinkenter::insertWorkLinkEnter($open_kfid,$external_userid,$scene,$sceneParams["kfid"],$sceneParams["record_id"],$msgList->send_time,$back_platfrom);
                            // 首次进入或者结束后重新进入,发送欢迎语
                            if (isset($msgList->event->welcome_code)) {
                                $sendMsg = self::sendWelcomeMsg($corp_id,$external_userid,$msgList->event->welcome_code,$open_kfid,$sceneParams["kfid"],$sceneParams["record_id"],$back_platfrom);
                            } else {
                                self::sendMsg($corp_id,$external_userid,$open_kfid,$sceneParams["kfid"],$sceneParams["record_id"],$back_platfrom);
                            }
                        } elseif ($event_type == "session_status_change") {
                            // 客服结束会话,回到智能客服
                            // self::addKfListsExternalMsg($msgList,[]);
                        }
                    } catch (Exception $e) {
                        Log::info("msgListsHanddle------2-start");
                        Log::info($e);
                        Log::info("msgListsHanddle------2-end");
                    }
                } else {
                    $open_kfid = $msgList->open_kfid;
                    $external_userid = $msgList->external_userid;
                    self::sendMsg($corp_id,$external_userid,$open_kfid,"","","");
                }
            } catch (Exception $e) {
                Log::info("msgListsHanddle------1-start");
                Log::info($e);
                Log::info("msgListsHanddle------1-end");
                continue;
            }
        }
    }

    // 发送欢迎语
    public static function sendWelcomeMsg($corp_id,$touser,$welcome_code,$open_kfid,$kfid,$record_id,$back_platfrom)
    {
        $params = self::getMenuText($kfid,$record_id,$back_platfrom);
        // 获取已配回复内容
        $msgid = md5($open_kfid.time().rand(10000,99999));
        $params["touser"] = $touser;
        $params["open_kfid"] = $open_kfid;
        $params["msgid"] = $msgid;
        $params["code"] = $welcome_code;
        $message = WorkkfService::sendMsgOnEvent($corp_id,$params);
        $send_status = ($message->errcode == 0) ? 2 : 3;
        $today = date("Ymd",time());
        Redis::hincrby('work_kefu_'.$today,$kfid,1);
        $workLinkRecord = new Worklinkrecord(["tbnum"=>$record_id[0]]);
        $workLinkRecord->updateWorkLinkKefuTime($record_id,time(),$send_status);
    }

    // 发送消息
    public static function sendMsg($corp_id,$touser,$open_kfid,$kfid,$record_id,$back_platfrom)
    {
        if (empty($kfid)) {
            $kefuRecord = Worklinkenter::getWorkLinkEnter($touser);
            if (empty($kefuRecord)) return "";
            $kfid = $kefuRecord["kfid"];
            $record_id = $kefuRecord["record_id"];
            $back_platfrom = $kefuRecord->back_platfrom;
        }
        $msgid = md5($open_kfid.time().rand(10000,99999));
        $params = self::getMenuText($kfid,$record_id,$back_platfrom);
        $params["touser"] = $touser;
        $params["open_kfid"] = $open_kfid;
        $params["msgid"] = $msgid;
        $message = WorkkfService::kfSendMsg($corp_id,$params);
    }

    public static function getMenuText($kfid,$record_id,$back_platfrom)
    {
        $linkWelcome = Cache::get("work_link_welcome_".$kfid);
        if(empty($linkWelcome)) {
            $linkWelcomes = Worklinkwelcome::workLinkWelcome($kfid);
            $linkWelcome = $linkWelcomes->msg_content;
            // 每次调用缓存30分钟
            Cache::put('work_link_welcome_'.$kfid,$linkWelcome,1800);
        }
        $welcome = json_decode($linkWelcome,true);
        $menu = [];
        $msgMenuLists = $welcome["msgmenu"]["list"];
        foreach ($msgMenuLists as $msgMenuList) {
            if ($msgMenuList["type"] == "view") {
                $msgMenuList["view"]["url"] = "https://kfq.xwwu.cn/qrcode/kf_qrcode.html?kfid=".$kfid."&record_id=".$record_id."&back_platfrom=".$back_platfrom;
            }
            $menu[] = $msgMenuList;
        }
        $welcome["msgmenu"]["list"] = $menu;
        return $welcome;
    }
}
